package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.PageResponseResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.common.minio.MinIOFileStorageService;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.*;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.PrivateKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private MinIOFileStorageService storageService;
    @Autowired
    private WmNewsMaterialMapper newsMaterialMapper;
    @Autowired
    private WmMaterialMapper materialMapper;

    @Override
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile multipartFile) {
        try {
            //校验参数
            if(multipartFile==null){
                throw new LeadNewsException(AppHttpCodeEnum.PARAM_INVALID);
            }

            //获取当前登录用户信息
            WmUser wmUser = (WmUser)ThreadLocalUtils.get();
            if(wmUser==null){
                throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
            }

            //上传文件到MinIO，获取url地址
            //生成随机文件名
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            //取出文件原名
            String originalFilename = multipartFile.getOriginalFilename();
            //获取文件后缀名
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            //最终的文件名
            String fieName = uuid+extName;
            try {
                String url = storageService.uploadImgFile("", fieName, multipartFile.getInputStream());
                //保存素材信息到DB
                WmMaterial wmMaterial = new WmMaterial();
                wmMaterial.setCreatedTime(new Date());
                wmMaterial.setUserId(wmUser.getId());
                wmMaterial.setType((short)0);
                wmMaterial.setIsCollection((short)0);
                wmMaterial.setUrl(url);
                save(wmMaterial);

                //返回新的素材信息（用于回显）
                return ResponseResult.okResult(wmMaterial);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage());
            }
        } finally {
            //清空ThreadLocal数据
            ThreadLocalUtils.remove();
        }
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        try {
            //校验参数
            dto.checkParam();
            if(dto.getIsCollection()==null)dto.setIsCollection((short)0);//0代表全部查询

            //获取当前登录用户信息
            WmUser wmUser = (WmUser)ThreadLocalUtils.get();
            if(wmUser==null){
                throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
            }

            //构建查询条件
            IPage<WmMaterial> iPage = new Page<>(dto.getPage(),dto.getSize());
            QueryWrapper<WmMaterial> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",wmUser.getId());//查询当前用户的素材

            //处理收藏条件
            if(dto.getIsCollection()==(short)1){
                queryWrapper.eq("is_collection",dto.getIsCollection());
            }

            //按照创建时间倒序
            queryWrapper.orderByDesc("created_time");

            //执行查询
            iPage = page(iPage,queryWrapper);

            //封装结果
            PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)iPage.getTotal());
            pageResponseResult.setData(iPage.getRecords());
            pageResponseResult.setErrorMessage("查询成功");

            //返回结果
            return pageResponseResult;
        } finally {
            ThreadLocalUtils.remove();
        }
    }

    //删除素材
    @Override
    public ResponseResult delPicture(Integer id) {

        if (id == null){
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //如果该素材已经绑定了文章，不能删除
        LambdaQueryWrapper<WmNewsMaterial> query = new LambdaQueryWrapper<>();
        query.eq(WmNewsMaterial::getMaterialId,id);
        Integer count = newsMaterialMapper.selectCount(query);

        if (count>0){
            throw new LeadNewsException(AppHttpCodeEnum.DATA_EXIST);
        }
        //在minio删除输出素材
        WmMaterial material = materialMapper.selectById(id);
        if (material == null){
            throw new LeadNewsException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        storageService.delete(material.getUrl());

        //删除素材表数据

        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmMaterial::getId,id);
        remove(wrapper);



        return ResponseResult.okResult(200,"删除素材成功");
    }

    //收藏素材
    @Override
    public ResponseResult collect(Integer id) {
        if (id == null){
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setIsCollection((short) 1);
        wmMaterial.setId(id);
        boolean result = updateById(wmMaterial);
        return ResponseResult.okResult(200,"收藏成功");
    }

    //取消收藏
    @Override
    public ResponseResult cancelCollect(Integer id) {
        if (id == null){
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setId(id);
        boolean result = updateById(wmMaterial);
        return ResponseResult.okResult(200,"取消收藏");
    }
}
